package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApCollectionServiceimpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Resource
    BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult collectArticle(CollectionBehaviorDto dto) {
        //参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();

        //查询行为实体是否存在
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApCollection collection = this.getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getEntryId()).eq(ApCollection::getEntryId, apBehaviorEntry.getId()));
        if (collection == null) {

            //封装添加数据
            ApCollection apCollection = new ApCollection();
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setCollectionTime(new Date());
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setPublishedTime(dto.getPublishedTime());
            apCollection.setType(dto.getType());
            //添加
            this.save(apCollection);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
